<template>
  <a-modal
    :title="'添加预分配单'"
    :visible.sync="topAddShow"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    width="90%"
    class="basic-modal"
  >
    <div class="title essence-item-container">
      <a-form-model
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 14 }"
        v-for="(item, index) in essenceItems"
        :key="index"
        ref="form"
        layout="inline"
      >
        <a-form-model-item label="预分配单号">
          <a-input v-model="item.OrderCode" placeholder="不填写自动生成" />
        </a-form-model-item>
        <a-form-model-item label="计划单号">
          <a-input disabled v-model="item.PackingPlanNo" />
        </a-form-model-item>
        <a-form-model-item label="超分配比例(%)">
          <a-input v-model="item.AllocationRatio" />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea v-model="item.Remarks" />
        </a-form-model-item>

        <a-form-model-item :wrapper-col="{ span: 24 }">
          <div style="display: flex; flex-wrap: wrap; flex-direction: column">
            <a-form-item
              v-for="(group, index) in item.SemiMGoodsDistributeDetailDtos"
              :key="index"
              style="margin-right: 20px"
            >
              <span>{{ group.MaterialCode }}：</span>
              <span class="total-amount">需求数量 {{ group.ReqQty }} </span>
              <span class="total-amount"
                >分配数量 {{ group.DistributeQty }}
              </span>
              <span
                class="total-amount"
                :class="{ negative: group.ReqQty - group.DistributeQty < 0 }"
              >
                剩余 {{ (group.ReqQty - group.DistributeQty).toFixed(3) }}
              </span>
            </a-form-item>
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>

    <div class="smiclass">
      <a-tabs type="card" default-active-key="1" :key="tabRenderKey">
        <a-tab-pane key="1" tab="精华液信息">
          <div class="operation-search">
            <a-form layout="inline" :form="searchItem">
              <a-form-item label="批次号：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.batchNo"
                />
              </a-form-item>
              <a-form-item label="投料单号：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchItem.planNo"
                />
              </a-form-item>
              <a-form-item>
                <a-button
                  class="default-button"
                  @click="getPackingPlansListFun(true)"
                >
                  查询
                </a-button>
              </a-form-item>
            </a-form>
          </div>
          <div>
            <div style="height: 410px">
              <a-table
                :columns="orderColums"
                :row-key="(record) => record.num"
                :data-source="orderList"
                :loading="loading1"
                :rowClassName="getRowClassName"
                :pagination="false"
                :scroll="{ x: 300, y: 400 }"
                size="middle"
              >
                <template slot="IfRecharged" slot-scope="text, record">
                  <a-checkbox
                    disabled
                    v-model="record.IfRecharged"
                  ></a-checkbox>
                </template>
                <template slot="IsQCLock" slot-scope="text, record">
                  <a-checkbox disabled v-model="record.IsQCLock"></a-checkbox>
                </template>
                <!-- 新增质检状态自定义渲染模板 -->
                <template slot="QMResult" slot-scope="text, record">
                  <a-tag
                    :color="getQMResultColor(record.QMResult)"
                    v-if="record.QMResult !== undefined"
                  >
                    {{ getQMResultText(record.QMResult) }}
                  </a-tag>
                </template>
                <template slot="DistributeQty" slot-scope="text, record">
                  <a-input-number
                    id="inputNumber"
                    :allowClear="true"
                    :min="0"
                    :max="record.ToDistributeQty"
                    placeholder="请输入"
                    :disabled="!showPlanTab"
                    v-model="record.DistributeQty"
                    @change="updateSelectedTotalQty"
                  />
                </template>
                <template slot="action" slot-scope="text, record">
                  <div class="chart-manage">
                    <general-button
                      :disabled="!record.AllocatedQty > 0"
                      @operation="alreadySmgrShow(record)"
                      btn-text="已分配"
                      class="small-button"
                    ></general-button>
                  </div>
                </template>
              </a-table>
            </div>
            <a-pagination
              v-show="false"
              show-size-changer
              :default-current="1"
              :pageSizeOptions="pageSizeOptions"
              :total="500"
              :pageSize="500"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane :disabled="!showPlanTab" key="2" tab="投料单信息">
          <div class="operation-search">
            <a-form layout="inline" :form="searchPlanItem">
              <a-form-item label="计划生产日期：">
                <a-range-picker
                  format="YYYY-MM-DD"
                  :default-value="defaulttimeList"
                  @change="onTime"
                  v-model="defaulttimeList"
                >
                  <template slot="dateRender" slot-scope="current">
                    <div
                      class="ant-calendar-date"
                      :style="getcurrentStyle(current)"
                    >
                      {{ current.date() }}
                    </div>
                  </template>
                </a-range-picker>
              </a-form-item>
              <a-form-item label="车间：">
                <a-select
                  :allowClear="true"
                  mode="multiple"
                  :maxTagCount="1"
                  class="selectwidth"
                  v-model="searchPlanItem.WSType"
                  placeholder="请选择"
                >
                  <a-select-option
                    v-for="item in wSTypeList"
                    :key="item.type"
                    :value="item.type"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="投料单号：">
                <a-input
                  :allowClear="true"
                  placeholder="请输入"
                  v-model="searchPlanItem.planNo"
                />
              </a-form-item>

              <a-form-item>
                <a-button class="default-button" @click="getPlansListFun">
                  查询
                </a-button>
              </a-form-item>
            </a-form>
          </div>
          <div>
            <div style="height: 410px">
              <a-table
                :columns="planOrderColums"
                :row-key="(record) => record.num"
                :data-source="planOrderList"
                :loading="loadingPlan1"
                :pagination="false"
                :scroll="{ x: 300, y: 400 }"
                size="middle"
              >
                <template slot="DistributeQty" slot-scope="text, record">
                  <a-input-number
                    id="inputNumber"
                    :allowClear="true"
                    :min="0"
                    :max="record.ToDistributeQty"
                    placeholder="请输入"
                    v-model="record.DistributeQty"
                    @change="updateSelectedTotalQty"
                  />
                </template>
              </a-table>
            </div>
            <a-pagination
              v-show="false"
              show-size-changer
              :default-current="1"
              :pageSizeOptions="pageSizeOptions"
              :total="500"
              :pageSize="500"
            />
          </div>
        </a-tab-pane>
      </a-tabs>
      <!-- <a-tabs type="card">
       
      </a-tabs> -->
    </div>

    <boottle-form v-model="boottleShow" @up-data="orderItemFun"></boottle-form>
    <!-- 查看已预分配弹窗 -->
    <already-form
      v-model="alreadyShow"
      :plan-no="alreadyData.PlanNo"
      :material-code="alreadyData.MaterialCode"
      :batch-no="alreadyData.BatchNo"
      @colse="alreadyShow = false"
    ></already-form>
  </a-modal>
</template>

<script>
import BoottleForm from "./table-selection-form.vue";
import { debounce } from "@/common/debounce";
import { getPreparationPlanData } from "@/api/SemiMGoodsDistributeDetail/index";
import {
  getSemiMGoodsRecordRequest,
  getSemiMGoodsRecordsByDistribute,
  insSemiMGoodsDistributeDetail,
} from "@/api/SemiMGoodsDistributeDetail/index";
import {
  insSemiMGoodsDistribute,
  updSemiMGoodsDistribute,
} from "@/api/SemiMGoodsDistribute/index";
import { GetWorkShopTypes } from "@/api/WorkShopType/index";
import { forEach } from "jszip";
import AlreadyForm from "../preAllocationDetails/essence-form-already.vue";
import GeneralButton from "@/components/be-current-btn.vue";
export default {
  components: {
    BoottleForm,
    GeneralButton,
    AlreadyForm,
  },
  props: {
    topAddShow: {
      type: Boolean,
      default: false,
    },
    essenceItem: {
      type: Object,
      default: {},
    },
    essenceItems: {
      type: Array,
      default: () => [
        {
          OrderCode: "",
          PackingPlanNo: "",
          AllocationRatio: 5,
          Remarks: "",
          PackingPlanID: null,
          SemiMGoodsDistributeDetails: [],
          PreparationPlanDtos: [],
        },
      ],
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  model: {
    prop: "topAddShow",
    event: "close",
  },

  data() {
    return {
      colResize: {
        isDragging: false,
        startX: 0,
        startWidth: 0,
        currentColIndex: -1,
      },
      boottleShow: false,
      feedShow: false,
      confirmLoading: false, //modal的loading
      confirmLoading: false, //modal的loading
      defaulttimeList: [], //默认时间
      expandedRowKeys: [],
      expandedRow: [],
      searchItem: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        materialNameCode: null,
        batchNo: null,
      }, //搜索参数
      orderColums: [
        {
          title: "序号",
          dataIndex: "num",
          fixed: "left",
          width: 50,
          align: "center",
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          sorter: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 1),
            },
          }),
        },
        {
          title: "投料单号",
          dataIndex: "PlanNo",
          align: "center",
          ellipsis: true,
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 2),
            },
          }),
        },
        {
          title: "精华液编码",
          dataIndex: "MaterialCode",
          sorter: true,
          align: "center",
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 3),
            },
          }),
        },
        {
          title: "精华液名称",
          dataIndex: "MaterialName",
          align: "center",
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 4),
            },
          }),
        },
        {
          title: "批次号",
          dataIndex: "BatchNo",
          align: "center",
          ellipsis: true,
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 5),
            },
          }),
        },
        {
          title: "当前库存",
          dataIndex: "CurQty",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "是否回抽料",
          dataIndex: "IfRecharged",
          key: "IfRecharged",
          ellipsis: true,
          align: "center",
          width: "100px",
          scopedSlots: { customRender: "IfRecharged" },
        },
        {
          title: "质检状态",
          dataIndex: "QMResult",
          align: "center",
          ellipsis: true,
          width: 80,
          scopedSlots: { customRender: "QMResult" }, // 添加自定义渲染槽位
        },
        {
          title: "质检锁定",
          dataIndex: "IsQCLock",
          align: "center",
          ellipsis: true,
          width: 80,
          scopedSlots: { customRender: "IsQCLock" },
        },
        {
          title: "待分配数量",
          dataIndex: "ToDistributeQty",
          align: "center",
          width: 100,
        },

        {
          title: "已分配数量",
          dataIndex: "AllocatedQty",
          align: "center",
          ellipsis: true,
          width: 100,
        },

        {
          title: "生产日期",
          dataIndex: "CreateDt",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "质检有效期",
          dataIndex: "ValidityDt",
          align: "center",
          ellipsis: true,
          width: 150,
        },
        {
          title: "分配数量",
          key: "DistributeQty",
          scopedSlots: { customRender: "DistributeQty" },
          fixed: "right",
          width: 120,
        },
        {
          title: "操作",
          dataIndex: "operate",
          width: 60,
          align: "center",
          fixed: "right",
          scopedSlots: { customRender: "action" },
        },
      ],
      orderList: [], //工单选择列表
      orderItem: { batchNo: null },
      orderListTotal: 0,
      pageSizeOptions: ["30", "50", "100", "200", "500", "1000"], //分页
      loading1: false,

      expandedPlanRowKeys: [],
      expandedPlanRow: [],
      searchPlanItem: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        planNo: null,
        packingPlanID: null,
      }, //搜索参数
      planOrderColums: [
        {
          title: "序号",
          dataIndex: "num",
          fixed: "left",
          width: 50,
          align: "center",
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          sorter: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 1),
            },
          }),
        },
        {
          title: "投料单号",
          dataIndex: "PlanNo",
          sorter: true,

          width: 120,
          align: "center",
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 20),
            },
          }),
        },
        {
          title: "生产批号",
          dataIndex: "BatchNo",
          align: "center",
          ellipsis: true,
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 21),
            },
          }),
        },
        {
          title: "产品编码",
          dataIndex: "MaterialCode",
          align: "center",
          ellipsis: true,
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 22),
            },
          }),
        },
        {
          title: "产品名称",
          dataIndex: "MaterialName",
          align: "center",
          ellipsis: true,
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 23),
            },
          }),
        },
        {
          title: "计划生产日期",
          dataIndex: "PlanDt",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "灌装单需求量",
          dataIndex: "ReqQty",
          align: "center",
          width: 100,
        },
        {
          title: "计划数量",
          dataIndex: "PlannedQuantity",
          align: "center",
          width: 100,
        },
        {
          title: "已分配数量",
          dataIndex: "AllocatedQty",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "分配数量",
          key: "DistributeQty",
          scopedSlots: { customRender: "DistributeQty" },
          fixed: "right",
          width: 150,
        },
      ],

      planDicStatus: [
        {
          type: 0,
          name: "初始",
        },
        {
          type: 2,
          name: "已下发",
        },
        {
          type: 3,
          name: "开始生产",
        },
        {
          type: 5,
          name: "结束生产",
        },
      ], //订单状态
      planOrderList: [],
      planOrderListTotal: 0,
      loadingPlan1: false,
      wSTypeList: [],
      selectedTotalQty: 0,
      remainingAllocationQty: 0, // 存储剩余分配数量
      selectedTabKey: "1", // 控制当前选中页签的 key
      tabRenderKey: 0, // 控制 a-tabs 重新渲染的 key
      alreadyShow: false, //已分配弹窗
      alreadyData: {}, //已分配的数据
    };
  },
  computed: {
    // 计算属性，当 essenceItems 数组为空或只有一个元素时显示投料单信息页签
    showPlanTab() {
      return this.essenceItems.length <= 1;
    },
  },
  methods: {
    // 确保统计方法包含所有分配数据（精华液+投料单）
    updateSelectedTotalQty() {
      // 直接使用完整数据列表（不依赖展开状态）
      const mergedData = [...this.orderList, ...this.planOrderList];

      const groupMap = mergedData.reduce((acc, item) => {
        const key = item.MaterialCode;
        if (!acc[key]) {
          acc[key] = {
            materialCode: key,
            totalQty: 0, // 总分配数量
          };
        }
        // 累加当前分配数量（过滤无效值）
        const distributeQty = Number(item.DistributeQty) || 0;
        acc[key].totalQty += distributeQty;
        return acc;
      }, {});

      // 计算全局总分配量（新增）
      const totalSum = Object.values(groupMap).reduce(
        (sum, group) => sum + group.totalQty,
        0
      );
      this.selectedTotalQty = parseFloat(totalSum.toFixed(3)); // 保留3位小数

      // 同步更新所有SemiMGoodsDistributeDetailDtos中的需求数量
      this.essenceItems.forEach((item) => {
        item.SemiMGoodsDistributeDetailDtos.forEach((group, index) => {
          const matched = groupMap[group.MaterialCode];
          if (matched) {
            this.$set(item.SemiMGoodsDistributeDetailDtos, index, {
              ...group,
              DistributeQty: matched.totalQty.toFixed(3), // 更新为当前物料总分配量
            });
          }
        });
      });
    },
    // 添加状态文本转换方法
    getQMResultText(value) {
      const map = { 0: "不合格", 1: "合格", 4: "待检" };
      return map[value] || "未知";
    },
    // 添加状态颜色转换方法
    getQMResultColor(value) {
      const colorMap = { 0: "#ff4d4f", 1: "#52c41a", 4: "#958900" };
      return colorMap[value] || "#bfbfbf";
    },
    //字体颜色
    getRowClassName(record) {
      const sevenDaysAgo = new Date().getTime() + 7 * 24 * 60 * 60 * 1000; // 计算7天前的时间戳（毫秒）
      // 根据行的某些条件来返回不同的类名
      if (new Date(record.ValidityDt).getTime() < new Date().getTime()) {
        return "rowRedClass";
      }
      if (new Date(record.ValidityDt).getTime() < sevenDaysAgo) {
        return "rowOrangeClass";
      }
      if (record.QMResult == 4 || record.IsQCLock == 1) {
        return "rowYellowClass";
      } else {
        return ""; // 或者返回null，表示不应用任何类名
      }
    },
    /** 新增精华液预分配 */
    async insData() {
      this.confirmLoading = true;
      try {
        // 验证分配数量
        let semiMGoodsDistributeDetails = this.orderList.filter(
          (itm) => itm.DistributeQty > 0
        );
        let preparationPlanDtos = this.planOrderList.filter(
          (itm) => itm.DistributeQty > 0
        );

        if (this.essenceItems.length > 1) {
          if (
            !semiMGoodsDistributeDetails ||
            semiMGoodsDistributeDetails.length == 0
          ) {
            this.$message.error("精华液列表没有输入预分配数量");
            return;
          }
        } else {
          if (
            (!semiMGoodsDistributeDetails ||
              semiMGoodsDistributeDetails.length == 0) &&
            (!preparationPlanDtos || preparationPlanDtos.length == 0)
          ) {
            this.$message.error("精华液列表或投料单列表没有输入预分配数量");
            return;
          }
        }

        let param = {
          SemiMGoodsDistributes: this.essenceItems,
          SemiMGoodsDistributeDetails: semiMGoodsDistributeDetails,
          PreparationPlanDtos: preparationPlanDtos,
        };
        const res = await insSemiMGoodsDistribute(param);

        if (res.Status !== 10000) {
          this.$message.error(`添加失败: ${res.Message}`);
          return;
        }
        this.$message.success("添加成功");
        this.$emit("up-data");
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.confirmLoading = false;
      }
    },
    //获取厂区列表
    async GetWorkShopTypesAllFun() {
      let that = this;

      let res = await GetWorkShopTypes({ segmentType: 0 });
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.WSType, name: item.WSName });
        });
        that.wSTypeList = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },

    //关闭弹窗
    handleCancel() {
      this.$emit("close", false);
    },
    //确认添加/修改
    handleOk() {
      this.insData();
    },

    /** 选择灌装单 */
    boottleFun() {
      this.boottleShow = true;
    },

    /** 灌装单赋值 */
    orderItemFun(item) {
      this.essenceItem.PackingPlanID = item.PackingPlanID;
      this.essenceItem.packingPlanNo = item.PackingPlanNo;
      this.essenceItem.PlanNos = [];
      this.essenceItem.AllocationRatio = 5;
      this.boottleShow = false;
      this.getPackingPlansListFun();
      this.GetPlansListFun();
    },
    //表格选择
    handleTableChange() {},

    // ... 已有代码 ...
    async getPackingPlansListFun(isSel = false) {
      let that = this;
      that.loading1 = true;
      that.expandedRowKeys = [];
      that.expandedRow = [];

      that.searchItem.PackingPlanIDs = [];
      // 检查 that.distributeList 是否为数组
      if (Array.isArray(that.essenceItems)) {
        that.essenceItems.forEach((item) => {
          that.searchItem.PackingPlanIDs.push(item.PackingPlanID);
        });
        that.searchItem.PackingPlanID = that.essenceItems[0]?.PackingPlanID;
      }

      let res = await getSemiMGoodsRecordsByDistribute(that.searchItem);
      if (res.Status == 10000) {
        that.orderList = res.Data.SemiMGoodsDistributeDetails;
        if (that.orderList) {
          that.orderList.forEach((item, index) => {
            item.num = index + 1;
            item.batchNo = item.BatchNo;
            item.id = item.MaterialCode + item.BatchNo + item.PlanNo;
            item.CreateDt = that.dateExt.showDate(item.CreateDt);
            item.ValidityDt = that.dateExt.showDateTime(item.ValidityDt);
          });
        }
        // 检查 res.Data.SemiMGoodsDistributes 是否为数组
        let data = res.Data.SemiMGoodsDistributes;
        if (Array.isArray(data)) {
          that.essenceItems.forEach((item) => {
            // 筛选 PackingPlanID 为空字符串的数据
            const matchedItems = data
              .filter((itm) => itm.PackingPlanID === item.PackingPlanID)
              .sort((a, b) => {
                // 按物料编码升序排序
                if (a.MaterialCode < b.MaterialCode) return -1;
                if (a.MaterialCode > b.MaterialCode) return 1;
                return 0;
              });
            if (matchedItems.length > 0) {
              item.SemiMGoodsDistributeDetailDtos = JSON.parse(
                JSON.stringify(matchedItems)
              );
            }
          });
        }
      } else {
        that.$message.error(res.Message);
      }
      that.loading1 = false;
    },
    //时间选择
    onTime(e, e1) {
      let that = this;
      that.searchPlanItem.StartDt = that.dateExt.showDate(e[0]._d);
      that.searchPlanItem.EndDt = that.dateExt.showDate(e[1]._d);
    },

    //时间选择器的样式填充
    getcurrentStyle(current, today) {
      const style = {};
      if (current.date() === 1) {
        style.border = "1px solid #1890ff";
        style.borderRadius = "50%";
      }
      return style;
    },
    //获取单据列表（投料单信息）
    getPlansListFun: debounce(async function () {
      let that = this;
      that.loadingPlan1 = true;
      that.searchPlanItem.PackingPlanIDs = [];
      // 检查 that.distributeList 是否为数组
      if (Array.isArray(that.essenceItems)) {
        that.essenceItems.forEach((item) => {
          that.searchPlanItem.PackingPlanIDs.push(item.PackingPlanID);
        });
        that.searchPlanItem.PackingPlanID = that.essenceItems[0]?.PackingPlanID;
      }
      let res = await getPreparationPlanData(that.searchPlanItem);
      if (res.Status == 10000) {
        that.planOrderList = res.Data.PreparationPlanDtos;
        if (that.planOrderList) {
          that.planOrderList.map((item, index) => {
            item.num = index + 1;
            item.PlanDt = that.dateExt.showDate(item.PlanDt);
          });
        }
      } else {
        that.$message.error(res.Message);
      }
      that.loadingPlan1 = false;
    }),
    handleResizeStart(e, colIndex) {
      e.preventDefault();
      const targetColumns =
        colIndex >= 20 ? this.planOrderColums : this.orderColums;

      this.colResize = {
        isDragging: true,
        startX: e.clientX,
        startWidth:
          targetColumns[colIndex >= 20 ? colIndex - 19 : colIndex].width, // 修正起始宽度获取
        currentColIndex: colIndex,
      };
      // 添加事件监听
      document.addEventListener("mousemove", this.handleResizing);
      document.addEventListener("mouseup", this.handleResizeEnd);
    },

    handleResizing(e) {
      if (!this.colResize.isDragging) return;

      // 判断当前操作的是哪个表格
      const isPlanOrder = this.colResize.currentColIndex >= 20;
      const actualIndex = isPlanOrder
        ? this.colResize.currentColIndex - 19 // 投料单列从20开始对应索引0
        : this.colResize.currentColIndex;

      const targetColumns = isPlanOrder
        ? this.planOrderColums
        : this.orderColums;

      const delta = e.clientX - this.colResize.startX;
      const newWidth = Math.max(50, this.colResize.startWidth + delta);

      // 更新对应的列数组
      const newColumns = targetColumns.map((col, index) => {
        if (index === actualIndex) {
          return { ...col, width: newWidth };
        }
        return col;
      });

      if (isPlanOrder) {
        this.planOrderColums = newColumns;
      } else {
        this.orderColums = newColumns;
      }
    },
    handleResizeEnd() {
      this.colResize.isDragging = false;
      this.colResize.currentColIndex = -1; // 重置当前列索引
      document.removeEventListener("mousemove", this.handleResizing);
      document.removeEventListener("mouseup", this.handleResizeEnd);
    },
    //已分配精华液
    alreadySmgrShow(item) {
      this.alreadyShow = true;
      this.alreadyData = item;
    },
  },

  watch: {
    topAddShow: {
      handler(newV, oldV) {
        if (newV) {
          this.tabRenderKey = Date.now(); // 弹窗打开时更新 key，触发重新渲染
          this.expandedRowKeys = [];
          this.expandedRow = [];
          this.searchItem.pageRequestModel.pageIndex = 1;
          this.expandedPlanRowKeys = [];
          this.expandedPlanRow = [];
          this.searchPlanItem.pageRequestModel.pageIndex = 1;
          // 重置时间筛选条件
          const startDate = this.dateExt.getDay(-30);
          const endDate = this.dateExt.getDay(30); // 当天

          this.searchPlanItem.StartDt = startDate;
          this.searchPlanItem.EndDt = endDate;
          this.defaulttimeList = [startDate, endDate];
          this.GetWorkShopTypesAllFun();
          this.getPackingPlansListFun(true);
          this.getPlansListFun();
          this.updateSelectedTotalQty(); // 初始化总数
        }
      },
      immediate: true, // 重点
      deep: true, // 重点
    },
  },
};
</script>

<style lang="less" scoped>
::v-deep .rowRedClass {
  color: #ff1818;
}
::v-deep .rowYellowClass {
  color: #958900;
}
::v-deep .rowOrangeClass {
  color: #ff8800;
}
.smiclass {
  display: flex;
  .left {
    flex: 2;
  }
  .right {
    flex: 1;
  }
}
.selectwidth {
  width: 15rem;
}
.ant-tabs {
  box-sizing: border-box;
  margin: 10px;
  padding: 0;
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5;
  list-style: none;
  font-feature-settings: "tnum";
  position: relative;
  overflow: hidden;
  zoom: 1;
}
.total-allocation-info {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  width: 100%;
  box-sizing: border-box;
}
.total-amount {
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-left: 8px;
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
  min-width: 80px;
  justify-content: center;

  &.negative {
    color: #ff4d4f;
  }
}
// 添加样式
::v-deep .ant-table-thead > tr > th {
  position: relative;
  user-select: none;

  &::after {
    content: "";
    position: absolute;
    right: -3px !important; // 扩大可拖拽区域
    top: 0;
    z-index: 1;
    width: 5px;
    height: 100%;
    cursor: col-resize;
    background-color: transparent;
    transition: background-color 0.3s;
  }

  &:hover::after {
    background-color: #1890ff;
  }
}

.ant-table-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.essence-item-container {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  &:not(:last-child) {
    margin-bottom: 24px;
  }
}
.small-button {
  padding: 0 8px;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
  border-radius: 2px;
  margin-right: 8px;
  text-align: center;
  cursor: pointer;
  display: flex;
  align-items: center;
}
</style>
